//
//  ZQKeyboardTextView.swift
//  Emoji002
//
//  Created by 钟清 on 17/4/12.
//  Copyright © 2017年 Zhong Qing. All rights reserved.
//

import UIKit

class ZQKeyboardTextView: UITextView {
    /* 插入表情 */
    func insertEmoticon(emoticon: KeyboardEmoticons) {
        /* emoji表情图文混排 */
        if let tempEmojiStr = emoticon.emoticonStr {
            let range = selectedTextRange!
            replaceRange(range, withText: tempEmojiStr)
            return
        }
        /* 新浪图片图文混排 */
        if let tempPngPath = emoticon.pngPath {
            /* 获得文本对应的属性字符串 */
            let attributeMStr = NSMutableAttributedString(attributedString: attributedText)
            /* 获取表情图片对应的属性字符串 */
            let attachment = KeyboardAttachment()
            attachment.emoticonChs = emoticon.chs
            let originFont = self.font!
            let fontHeight = originFont.lineHeight
            attachment.bounds = CGRect(x: 0, y: -2, width: fontHeight, height: fontHeight)
            attachment.image = UIImage(contentsOfFile: tempPngPath)
            let imageAttributeStr = NSAttributedString(attachment: attachment)
            /* 光标定位及替换 */
            let range = selectedRange
            attributeMStr.replaceCharactersInRange(range, withAttributedString: imageAttributeStr)
            /* 显示 */
            self.attributedText = attributeMStr
            /* 光标位置重新确定 */
            self.selectedRange = NSRange(location: range.location + 1, length: 0)
            /* 属性字符串大小重新设定 */
            self.font = originFont
            return
        }
        /* 删除最近一个文字或者图片 */
        if emoticon.isRemoveButton {
            deleteBackward()
        }
    }
    /* 获取插入了表情的字符串 */
    func getEmoticonStr() -> String {
        /* 获取整个字符串的range */
        let range = NSRange(location: 0, length: attributedText.length)
        /* 创建可变字符串用来拼接保存 */
        var mutableStr = String()
        /* 遍历属性字符串 */
        attributedText.enumerateAttributesInRange(range, options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict, range, _) in
            if let tempAttachment = dict["NSAttachment"] as? KeyboardAttachment { // 表情属性字符串
                mutableStr += tempAttachment.emoticonChs!
            } else { // 文字属性字符串
                mutableStr += (self.text as NSString).substringWithRange(range)
            }
        }
        return mutableStr
    }
}
